class Solution {
    public int maxProfit(int[] prices) {
        // 创建 dp 表、初始化、填表、返回值
        int n = prices.length;
        int[][] f = new int[n][3];
        int[][] g = new int[n][3];

        f[0][0] = -prices[0];
        f[0][1] = -0x3f3f3f;
        f[0][2] = -0x3f3f3f;
        g[0][1] = -0x3f3f3f;
        g[0][2] = -0x3f3f3f;
        
        for (int i = 1; i < n; i++) {
            for (int j = 0; j < 3; j++) {
                f[i][j] = Math.max(f[i-1][j], g[i-1][j]-prices[i]);
                g[i][j] = g[i-1][j];
                if (j-1 >= 0) {
                    g[i][j] = Math.max(f[i-1][j-1]+prices[i], g[i][j]);
                }
            }
        }

        return Math.max(Math.max(g[n-1][0], g[n-1][1]), g[n-1][2]);
    }
}